package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.common.exception.LyException;
import com.leyou.dto.BrandDTO;
import com.leyou.entity.Brand;
import com.leyou.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import com.mysql.jdbc.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PutMapping;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {
    @Autowired
    private CategoryBrandService categoryBrandService;

    @Override
    public PageDTO<BrandDTO> queryBrandByPage(Integer page, Integer rows, String key) {
        // 1.分页信息的健壮性处理
        page = Math.min(page, 100);
        rows = Math.max(rows, 5);
        // 2.分页
        Page<Brand> info = new Page<>(page, rows);
        // 3.判断key是否存在
        boolean isKeyExists = StringUtils.isNullOrEmpty(key);
        // 4.如果key存在，添加like和eq的查询条件，否则不添加
        query().like(!isKeyExists, "name", key)
                .or()
                .eq(!isKeyExists, "letter", key)
                .page(info);
        // 5.封装结果
        List<Brand> list = info.getRecords();
        //System.out.println("-==========list========= = " + list);
        return new PageDTO<>(info.getTotal(), info.getPages(), BrandDTO.convertEntityList(list));
    }


    @Override
    public Brand queryBrandById(Long id) {
        Brand brand = getById(id);
        return brand;
    }

    @Override
    public List<BrandDTO> queryBrandByCategory(Long id) {
        List<Brand> list = getBaseMapper().queryBrandByCategory(id);
        return BrandDTO.convertEntityList(list);
    }
    @Transactional
    @Override
    public void savebrand(BrandDTO brandDTO) {
        //先转化为po
        //再新增品牌id
        //最后更改中间表
        Brand brand = brandDTO.toEntity(Brand.class);
        this.save(brand);
        //更新中间表
        //批量更新中间表
        List<CategoryBrand> collect = brandDTO.getCategoryIds().stream()
                .map(ling -> CategoryBrand.of(ling, brand.getId()))
                .collect(Collectors.toList());
        //批量更新中间表
        categoryBrandService.saveBatch(collect);

    }

    @Override
    @Transactional
    public void updateBrand(BrandDTO brandDTO) {
        //转化为po对象
        Brand brand = brandDTO.toEntity(Brand.class);
        //更新brand表
        boolean b = this.updateById(brand);
        if (!b){
            //不成功后面的不需要执行下去
            //抛出异常
            throw new LyException(500,"更新品牌失败~~");
        }
        //先删除中间表信息
        //删除前先执行查询quety
        boolean success1 = categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id", brandDTO.getId()));
        if (!success1){
            throw new LyException(500,"更新品牌失败,删除中间表数据出错~~");
        }
        //重新插入中间表数据
        List<CategoryBrand> collect = brandDTO.getCategoryIds().stream()
                .map(id -> CategoryBrand.of(id, brandDTO.getId()))
                .collect(Collectors.toList());
        //批量插入中间表
        categoryBrandService.saveBatch(collect);

    }

    @Override
    @Transactional
    public void deleteByid(Long id) {
        //先删除中间表
        //再删除品牌表
        boolean ling = categoryBrandService.remove(
                new QueryWrapper<CategoryBrand>().eq("brand_id", id));

        if (!ling){
            throw new LyException(500,"删除中间表失败~~");
        }
        //再删除品牌表
        this.removeById(id);
    }
}

